<template>
    <div style="width:100%;height:100%;">
        <component v-if="!url  && !show" ref="current" :is="currentView"
                   :menuId="curMenu.id" :menuParams="curMenu.params"
                   :destroy="destroy" :layerid="layerid"></component>
        <iframe v-else-if="url && show" style="height:700px;width:100%;"
                id="iframeId" :src="url" frameborder="0" scrolling="auto">
        </iframe>
    </div>
</template>

<script>
import {TokenUtil} from "@lowcode/jpaas-base-lib";
import useMain from "@/stores/useMain.js";
import { storeToRefs } from 'pinia';

export default {
    name: "IframeView",
    props:["currentView","layerid","destroy","menu"],
    setup(){
        let {layout,selectedMenuKey,menus} = storeToRefs(useMain())
        return {
            layout,selectedMenuKey,menus
        }
    },
    data() {
        return {
            curMenu:{},
            url:"",
            show: false
        }
    },
    created() {
        this.init()
    },
    methods:{
        init(){
            let menu =this.getMenuByMenuKey();
            let _menu=this.menu?this.menu:menu;
            if(_menu && _menu.settingType=="iframe"){
                this.show=true;
                this.url=_menu.params;
                let token = TokenUtil.getToken();
                this.completeTokenVale(token);
                if (this.url.indexOf("?") == -1) {
                    this.url += "?authorization=" + token;
                } else {
                    this.url += "&authorization=" + token;
                }
            }else {
                this.curMenu=_menu;
            }
        },
        completeTokenVale(token) {
            //let token = this.getToken();
            // 首先判断URL中是否已包含accessToken参数
            if (!this.url.includes("accessToken")) {
                // 如果URL中没有accessToken参数，那么就在URL的查询字符串中添加它，并将其值设置为token
                this.url += (this.url.includes("?") ? "&" : "?") + `accessToken=${token}`;
            } else {
                // 如果URL中已经有了accessToken参数，就获取它的当前值
                const urlParams = new URLSearchParams(this.url.split("?")[1]);
                const currentToken = urlParams.get("accessToken");

                // 判断accessToken是否有值
                if (!currentToken) {
                    // 如果accessToken的值为空或未定义，就用新的token值来更新它
                    urlParams.set("accessToken", token);
                    this.url = `${this.url.split("?")[0]}?${urlParams.toString()}`;
                }
            }
        },
        getMenuByMenuKey(){
            return this.menus.find(item=> {return item.menuKey==this.selectedMenuKey});
        }
    },
    watch: {
        'selectMenu': {
            handler: function (val, old) {
                this.show = false;
                this.$nextTick(() => {
                    this.init()
                })
            }
        },
        deep: true
    }
}
</script>

<style scoped>

</style>
